package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
//        Shop shop = queryWithPassThrough(id);
        //缓存击穿
        Shop shop = queryWithMutex(id);
        // 逻辑过期
//        Shop shop = queryWithLogicalExpire(id);
        // 做空数据判断
        if (shop == null) {
            return Result.fail("商铺不存在！");
        }
        return Result.ok(shop);
    }

    // 创建一个线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(5);


    // 逻辑过期
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 根据商铺id查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断是否缓存命中
        if (StrUtil.isBlank(shopJson)) {
            // 未命中 直接返回
            return null;
        }
        // 命中 判断缓存是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())){
            // 未过期，返回商铺信息
            return shop;
        }
        // 过期，获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = TryLock(lockKey);
        //判断是否获取到锁
        if (isLock){
            // 获取到锁，开启独立线程进行查询数据库和写入redis
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    // 重建缓存
                    saveShop2Redis(id,LOCK_SHOP_TTL);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    // 释放锁
                    NuLock(lockKey);
                }
            });

        }
        // 为获取到锁 返回过期商铺信息
        return shop;
    }

    // 逻辑过期根据id查询数据库，并写入redis
    public void saveShop2Redis(Long id,Long expireSeconds){
        // 查询店铺数据
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
    }


    // 使用互斥锁解决缓存击穿
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 根据商铺id查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断是否缓存命中
        if (StrUtil.isNotBlank(shopJson)) {
            // 命中 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        if (shopJson != null){
            return null;
        }

        String lockKey = LOCK_SHOP_KEY +id;
        Shop shop = null;
        try {
            // 未命中 获取锁
            boolean isLock = TryLock(lockKey);
            //判断是否获取到锁
            if (!isLock){
                // 未获取到 休眠一段时间并重试
                Thread.sleep(50); // 休眠50毫秒
                // 重试回调
                return queryWithMutex(id);
            }
            // 获取到
            // 查询数据库
            shop = getById(id);
            // 判断商铺是否存在
            if (shop == null) {
                // 不存在返回404
                stringRedisTemplate.opsForValue().set(key, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 存在将数据写入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            // 释放锁
            NuLock(lockKey);
        }
        // 返回
        return shop;
    }


    // 解决缓存穿透
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        // 根据商铺id查询redis缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        // 判断是否缓存命中
        if (StrUtil.isNotBlank(shopJson)) {
            // 命中 直接返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }

        if (shopJson != null){
            return null;
        }

        // 未命中，查询数据库
        Shop shop = getById(id);
        // 判断商铺是否存在
        if (shop == null) {
            // 不存在返回404
            stringRedisTemplate.opsForValue().set(key, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 存在将数据写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 返回
        return shop;
    }

    // 获取互斥锁
    public boolean TryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    // 释放锁
    public void NuLock(String key){
        stringRedisTemplate.delete(key);
    }


    @Override
    @Transactional
    public Result update(Shop shop) {
        // 获取商铺id
        Long id = shop.getId();
        // 判断商铺id是否为空
        if (id == null) {
            return Result.fail("商铺Id不存在");
        }
        // 写入数据库
        updateById(shop);
        // 删除redis缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryShopType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要根据坐标查询
        if (x == null || y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        // 查询redis,按照距离排序，分页，结果： shopId,distance
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
        );
        if (results == null){
            return Result.ok(Collections.emptyList());
        }
        // 解析id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 获取店铺id
            String shoIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shoIdStr));
            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shoIdStr,distance);
        });
        // 根据id查询shop
        String idsStr = StrUtil.join(",",ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 返回
        return Result.ok(shops);
    }
}
